package com.qen.common;

import org.beetl.sql.clazz.kit.BeetlSQLException;

import java.util.ArrayList;
import java.util.List;

/**
 * 类操作功能
 *
 * @author licz
 * @data 2025年05月16日 5:51 PM
 */
public class ClassUtils {

    /**
     * @param name
     * @param classLoader
     * @return
     * @since 1.0.0
     */
    public static Class<?> toClassConfident(String name, ClassLoader classLoader) {
        try {
            return loadClass(name, getClassLoaders(classLoader));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new BeetlSQLException(BeetlSQLException.ERROR, "找不到指定的class！请仅在明确确定会有 class 的时候，调用该方法", e);
        }
    }

    private static Class<?> loadClass(String className, ClassLoader[] classLoaders) throws ClassNotFoundException {
        for (ClassLoader classLoader : classLoaders) {
            if (classLoader != null) {
                try {
                    return Class.forName(className, true, classLoader);
                } catch (ClassNotFoundException e) {
                    // ignore
                }
            }
        }
        throw new ClassNotFoundException("Cannot find class: " + className);
    }

    private static ClassLoader[] getClassLoaders(ClassLoader classLoader) {
        return new ClassLoader[]{
                classLoader,
                Thread.currentThread().getContextClassLoader(),
                ClassUtils.class.getClassLoader(),
        };
    }

    /**
     * 获取当前类的所有父类（不包含自身，包含 Object）
     */
    public static List<Class<?>> getAllSuperClasses(Class<?> clazz) {
        List<Class<?>> superClasses = new ArrayList<>();

        Class<?> superClass = clazz.getSuperclass();
        while (superClass != null) {
            superClasses.add(superClass);
            superClass = superClass.getSuperclass();
        }

        return superClasses;
    }

}
